package com.platform.comm.common.batch.writer;

import com.platform.comm.util.ProjectUtils;
import com.platform.comm.util.UploadUtil;
import com.platform.vo.ExcelCfgDto;
import com.platform.vo.ImportDto;
import com.platform.comm.common.batch.ComBatchExportContext;
import com.platform.comm.util.NcExcelTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.item.ItemWriter;
import org.springframework.lang.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

/**
 * 系统管理批量导出
 * @author Tommy
 */
@Slf4j
public class SysExpItemWriter implements ItemWriter<ImportDto>, StepExecutionListener {
    private static final Integer WORKBOOK_CACHE_ROWS = 100;
    private ComBatchExportContext context;

    private Integer currRowNum = 0;
    private SXSSFWorkbook workbook;
    private Sheet sheet;

    public SysExpItemWriter(ComBatchExportContext context){
        this.context = context;
    }

    @Override
    public void beforeStep(@NonNull StepExecution stepExecution) {
        workbook = new SXSSFWorkbook(WORKBOOK_CACHE_ROWS);
        openSheet();
        sheet.setDefaultColumnWidth(20);

        this.currRowNum = context.getExportConfig().getFirstRowNum();
        NcExcelTools.putTitle(sheet, context.getExportConfig());
        currRowNum++;
    }

    @Override
    public ExitStatus afterStep(@NonNull StepExecution stepExecution) {
        String time = stepExecution.getJobExecution().getJobParameters().getString("time");
        String moduleFilePath = UploadUtil.buildStdPath(context.getParams().get("moduleName"), time);
        File file = new File(ProjectUtils.getExcelExportFilePath("sys", moduleFilePath));

        if(!file.getParentFile().exists()){
            if(!file.getParentFile().mkdirs()){
                log.error("创建文件夹{}错误", file.getParentFile().getAbsolutePath());
                return ExitStatus.FAILED;
            }
        }

        context.setFilePath(file.getAbsolutePath());

        try (FileOutputStream fos = new FileOutputStream(file)){
            workbook.write(fos);
        }catch (IOException e){
            log.error(e.getMessage(), e);
            return ExitStatus.FAILED;
        }
        return ExitStatus.COMPLETED;
    }

    @Override
    public void write(List<? extends ImportDto> items) {
        ExcelCfgDto config = context.getExportConfig();
        for (ImportDto item : items) {
            Row row = NcExcelTools.createRow(sheet, currRowNum);
            NcExcelTools.putRow(row, config, item);
            currRowNum++;
        }

        // 每个sheet最大记录行数为1百万
        Long maxRowNum = 1000000L;
        if (maxRowNum < currRowNum) {
            openSheet();
            NcExcelTools.putTitle(sheet, context.getExportConfig());
            this.currRowNum = config.getFirstRowNum();
        }
    }

    private void openSheet() {
        if (this.workbook != null) {
            this.sheet = this.workbook.createSheet();
        }
    }
}
